package com.gombe.credit.app.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.view.Gravity
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.databinding.ActGombeCreditPermissionsPageBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditPermission
import com.gombe.credit.app.ui.dialog.DialogGombeCreditTips
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.decoration.LinearSpacingItemDecoration
import com.gombe.credit.app.utils.helper.GombeCreditPermissionHelper
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:04
 * @Annotation：权限
 */
class ActGombeCreditPermissions: CommonActivity(),EasyPermissions.RationaleCallbacks {
    lateinit var binding: ActGombeCreditPermissionsPageBinding

    private val PERMISSION_REQUEST_CODE : Int = 100;
    private var permissionAdapter: AdapterGombeCreditPermission? = null

    companion object {
        private const val INTENT_KEY_AMOUNT = "amount"
        fun start(context: Context, amount: String) {
            val intent = Intent(context, ActGombeCreditPermissions::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            context.startActivity(intent)
        }
    }

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditPermissionsPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)
        setGombeCreditTitleBarVisibility(View.VISIBLE)
        setGombeCreditTextTitle(getString(R.string.gombe_credit_permission_title))
        initGombeCreditPermissionListView()
        binding.permissionContentLayout.visibility = View.INVISIBLE
    }

    override fun initGombeCreditListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Permission Page")
            }
        })
        //拒绝
        binding.btnDeny.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS,-1)
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_DENY,"Permission Page")

                val intent = intent
                intent.putExtra("isPermissionAgree",false)
                setResult(RESULT_OK,intent)
                finish()
            }
        })
        //同意
        binding.btnAgree.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_AGREE,"Permission Page")
                if (!binding.permissionReadCheckBox.isChecked){
                    showRequestPermissionTipsDialog()
                    return
                }
                requestGombeCreditPermissionAction()
            }
        })
    }

    override fun takeGombeCreditData() {
        takeGombeCreditPermissionDataList()
    }

    /**
     * 初始化权限列表
     */
    private fun initGombeCreditPermissionListView(){
        binding.permissionListView.setHasFixedSize(true)
        binding.permissionListView.isNestedScrollingEnabled = false
        binding.permissionListView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = GombeCreditDensityUtil.dp2px(16f)
        binding.permissionListView.addItemDecoration(LinearSpacingItemDecoration(topDecoration, topDecoration,topDecoration,topDecoration))
        binding.permissionListView.layoutManager = LinearLayoutManager(this)
        permissionAdapter = AdapterGombeCreditPermission(binding.permissionListView)
        binding.permissionListView.adapter = permissionAdapter
        binding.permissionListView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        GombeCreditLogger.e("Permission page onPermissionsGranted, code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_AGREE,Manifest.permission.READ_SMS)

            val intent = intent
            intent.putExtra("isPermissionAgree",true)
            setResult(RESULT_OK,intent)
            finish()
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        GombeCreditLogger.e("onPermissionsDenied code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_DENY, Manifest.permission.READ_SMS)
            GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS,-1)

            //是否是广告渠道
            val isAdSource = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_IS_ADSOURCE)
            if (isAdSource){//广告渠道，拒绝后引导去设置里打开
                // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    AppSettingsDialog.Builder(this)
                        .build().show()
                }
            } else {//非广告渠道，拒绝后依然进入下一步
                val intent = intent
                intent.putExtra("isPermissionAgree",false)
                setResult(RESULT_OK,intent)
                finish()
            }
        }

        // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            // 设置 引导用户前往设置界面 自行设置权限的引导对话框
//            AppSettingsDialog.Builder(this)
////                .setTitle("需要手动设置权限")
////                .setRationale("存在永久拒绝的权限 , 需要手动前往设置界面为应用进行授权")
////                .setPositiveButton("前往设置界面")
////                .setNegativeButton("不使用该功能")
//                .build().show()
//        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        GombeCreditLogger.e("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        GombeCreditLogger.e("onRationaleDenied, code: $requestCode")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE){
            // 判断权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(this, Manifest.permission.READ_SMS)
            if (hasPermissions){
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_AGREE,Manifest.permission.READ_SMS)

                val intent = intent
                intent.putExtra("isPermissionAgree",true)
                setResult(RESULT_OK,intent)
                finish()
            }
        }
    }

    /**
     * 加载权限列表
     */
    private fun takeGombeCreditPermissionDataList(){
        //显示额度 = 额度 / 2
        val showAmount = BigDecimal(takeGombeCreditIntentProductAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        val permissionList = arrayListOf<JSONObject>()
        val item1 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem1()
        item1.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.15")).stripTrailingZeros().toPlainString())
        item1.put("passRate","30")
        permissionList.add(item1)

        val item2 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem2()
        item2.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        item2.put("passRate","10")
        permissionList.add(item2)

        val item3 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem3()
        item3.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        item3.put("passRate","10")
        permissionList.add(item3)

        val item4 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem4()
        item4.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        item4.put("passRate","10")
        permissionList.add(item4)

        val item5 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem5()
        item5.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        item5.put("passRate","10")
        permissionList.add(item5)

        val item6 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem6()
        item6.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        item6.put("passRate","10")
        permissionList.add(item6)

        val item7 = GombeCreditPermissionHelper.queryGombeCreditPermissionItem7()
        item7.put("loanAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        item7.put("passRate","10")
        permissionList.add(item7)

        lifecycleScope.launch {
            delay(200)
            permissionAdapter?.data = permissionList
            binding.permissionContentLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 获取产品额度
     */
    private fun takeGombeCreditIntentProductAmount(): String{
        return intent.extras?.getString(INTENT_KEY_AMOUNT,"").toString()
    }

    /**
     * 提示dialog
     */
    private fun showRequestPermissionTipsDialog(){
        val requestPermission = Manifest.permission.READ_SMS
        val dialog = DialogGombeCreditTips(this,requestPermission, object : DialogGombeCreditTips.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.buttonConfirm -> {
                        requestGombeCreditPermissionAction()
                    }
                    R.id.buttonCancel -> {
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_DENY,requestPermission)
                    }
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.setGombeCreditKindTipsIconResource(R.mipmap.gombe_credit_image_dialog_tips_icon)
        dialog.setGombeCreditKindTipsTitleText(getString(R.string.gombe_credit_dialog_kind_tips_title),getColor(R.color.gombe_credit_ff1d1e20))
        dialog.setGombeCreditKindTipsMsgText(getString(R.string.gombe_credit_permission_dialog_agree_tips))
        dialog.setGombeCreditKindTipsMsgGravity(Gravity.CENTER)
        dialog.isGombeCreditKindTipsDoubleButton(true)
        dialog.setGombeCreditKindTipsButtonCancelText(getString(R.string.gombe_credit_button_cancel))
        dialog.setGombeCreditKindTipsButtonCancelBackgroundResource(getColor(R.color.gombe_credit_FFF9F9F7))
        dialog.setGombeCreditKintTipsButtonConfirmText(getString(R.string.gombe_credit_button_ok))
        dialog.setGombeCreditKindTipsButtonConfirmBackgroundResource(getColor(R.color.theme))
    }

    /**
     * 申请权限
     */
    private fun requestGombeCreditPermissionAction(){
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS,1)
        // TODO:  权限说明
        val requestReason = getString(R.string.gombe_credit_permission_sms_why_reason) + "\n" + getString(R.string.gombe_credit_permission_sms_do_reason) + "\n" + getString(R.string.gombe_credit_permission_sms_data_safety_reason)
        EasyPermissions.requestPermissions(this@ActGombeCreditPermissions, requestReason,PERMISSION_REQUEST_CODE,Manifest.permission.READ_SMS)
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.PERMISSION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.PERMISSION_END)
    }
}